package com.xbongbong.sso.help;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.enums.EnableEnum;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.pro.config.ProBaseConfig;
import com.xbongbong.pro.enums.errorcodes.SsoErrorCodeEnum;
import com.xbongbong.sso.domain.entity.OauthConnectorEntity;
import com.xbongbong.sso.enums.AccountRuleEnum;
import com.xbongbong.sso.enums.OauthFieldEnum;
import com.xbongbong.sso.enums.OauthTypeEnum;
import com.xbongbong.sso.model.OauthConnectorModel;
import com.xbongbong.sso.pojo.OauthConnectorPojo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * 授权连接器帮助类
 */
@Component
public class OauthConnectorHelp {

    private static final Logger LOG = LoggerFactory.getLogger(OauthConnectorHelp.class);


    @Resource
    private OauthConnectorModel oauthConnectorModel;
    @Resource
    private ProBaseConfig proBaseConfig;

    public OauthConnectorPojo oauthConnectorPojoFormat(OauthConnectorEntity oauthConnector) throws XbbException {
        if (Objects.isNull(oauthConnector)) {
            return null;
        }
        String connectorSign = oauthConnector.getConnectorSign();
        OauthConnectorPojo oauthConnectorPojo = new OauthConnectorPojo();
        oauthConnectorPojo.setId(oauthConnector.getId());
        oauthConnectorPojo.setCorpid(oauthConnector.getCorpid());
        oauthConnectorPojo.setWebLoginUrl(formatLoginUrl(connectorSign));
        JSONObject enableJson = new JSONObject();
        enableJson.put("value", oauthConnector.getEnable());
        enableJson.put("text", EnableEnum.getByCode(oauthConnector.getEnable()).getMemo());
        oauthConnectorPojo.setEnable(enableJson);
        JSONObject typeJson = new JSONObject();
        typeJson.put("value", oauthConnector.getType());
        typeJson.put("text", OauthTypeEnum.getByCode(oauthConnector.getType()).getName());
        oauthConnectorPojo.setType(typeJson);
        oauthConnectorPojo.setName(oauthConnector.getName());
        oauthConnectorPojo.setConnectorSign(connectorSign);
        oauthConnectorPojo.setRedirectUrl(formatRedirectUrl(connectorSign));
        oauthConnectorPojo.setClientId(oauthConnector.getClientId());
        oauthConnectorPojo.setClientSecret(oauthConnector.getClientSecret());
        JSONObject accountRuleJson = new JSONObject();
        accountRuleJson.put("value", oauthConnector.getAccountRule());
        accountRuleJson.put("text", AccountRuleEnum.getByCode(oauthConnector.getAccountRule()).getName());
        oauthConnectorPojo.setAccountRule(accountRuleJson);
        Integer directSsoLogin = oauthConnector.getDirectSsoLogin();
        JSONObject directSsoLoginJson = new JSONObject();
        if (Objects.isNull(directSsoLogin)) {
            directSsoLogin = EnableEnum.OPEN.getCode();
        }
        directSsoLoginJson.put("value", directSsoLogin);
        directSsoLoginJson.put("text", EnableEnum.getByCode(directSsoLogin).getMemo());
        oauthConnectorPojo.setDirectSsoLogin(directSsoLoginJson);

        oauthConnectorPojo.setUpdateTime(oauthConnector.getUpdateTime());
        oauthConnectorPojo.setAddTime(oauthConnector.getAddTime());
        oauthConnectorPojo.setDel(oauthConnector.getDel());
        return oauthConnectorPojo;
    }

    public String getLoginUrlFromDb(String connectorSign) throws XbbException {
        OauthConnectorEntity oauthConnector = oauthConnectorModel.getByConnectorSign(connectorSign);
        if (Objects.isNull(oauthConnector)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
        }
        return formatLoginUrl( connectorSign);
    }

    public String formatLoginUrl(String connectorSign) throws XbbException {
        String ssoLoginUrl = proBaseConfig.getSsoLoginUrl();
        return String.format(ssoLoginUrl, connectorSign);
    }

    public String getRedirectUrlFromDb(String connectorSign) throws XbbException {
        OauthConnectorEntity oauthConnector = oauthConnectorModel.getByConnectorSign(connectorSign);
        if (Objects.isNull(oauthConnector)) {
            throw new XbbException(SsoErrorCodeEnum.API_ERROR_273003);
        }
        return formatRedirectUrl(connectorSign);
    }

    public String formatRedirectUrl(String connectorSign) {
        String ssoRedirectUrl = proBaseConfig.getSsoRedirectUrl();
        return String.format(ssoRedirectUrl, connectorSign);
    }

    /**
     * 获取初始化系统字段（没有接收过三方参数）
     * 设置好的常量：
     * client_id
     * client_secret
     * redirect_url
     *
     * 通过接收IDP的参数（这部分需要在过程中获取）：
     * auth_code
     * access_token
     * identity_authentication
     * @param oauthConnector
     * @return
     */
    public Map<String, String> initSysParameter(OauthConnectorEntity oauthConnector) {
        String clientId = oauthConnector.getClientId();
        String clientSecret = oauthConnector.getClientSecret();
        String ssoRedirectUrl = formatRedirectUrl(oauthConnector.getConnectorSign());

        Map<String, String> sysParameter = new HashMap<>();
        sysParameter.put(OauthFieldEnum.CLIENT_ID.getAttr(), "\"" + clientId + "\"");
        sysParameter.put(OauthFieldEnum.CLIENT_SECRET.getAttr(), "\"" + clientSecret + "\"");
        sysParameter.put(OauthFieldEnum.REDIRECT_URL.getAttr(), "\""+ ssoRedirectUrl + "\"");
        return sysParameter;
    }

    /**
     * 判断connectorSign是否重复
     * @param id 编辑时，传授权连接器id，新建时传null
     * @param connectorSign 授权连接器唯一标识
     * @return
     */
    public boolean connectorSignRepeat(Long id, String connectorSign) {
        Map<String, Object> param = new HashMap<>();
        param.put("idNeq", id);
        param.put("connectorSign", connectorSign);
        param.put("del", 0);
        Integer count = oauthConnectorModel.getEntitiesCount(param);
        return  count > 0;
    }
}
